from PySide2.QtWidgets import QWidget, QLabel, QPushButton, QSlider, QHBoxLayout, QVBoxLayout
from PySide2.QtCore import Qt

from custom.VideoPlayer import VideoPlayer
from custom.VideoPlayer import *


class VideoWidget(QWidget):

    def __init__(self):
        super(VideoWidget, self).__init__()
        self.slder_video_pressed = False  # 判断当前进度条识别否被鼠标点击

        self.setupUi()

    def setupUi(self):
        self.layout = QVBoxLayout(self)
        
        self.player = VideoPlayer()
        self.player.progressChanged.connect(self.playerProgressChanged)
        self.player.stateChanged.connect(self.playerStateChanged)

        self.layout.addWidget(self.player)

        self.hboxBar = QHBoxLayout()
        self.layout.addLayout(self.hboxBar)

        self.playButton = QPushButton("播放")
        self.playButton.clicked.connect(self.onClickPlay)

        self.currentLabel = QLabel("00:00")
        self.totalLable = QLabel("00:00")

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setTracking(False)
        self.slider.sliderReleased.connect(self.releaseSlider)
        self.slider.sliderPressed.connect(self.pressSlider)
        self.slider.sliderMoved.connect(self.moveSlider)

        self.hboxBar.addWidget(self.playButton)
        self.hboxBar.addWidget(self.currentLabel)
        self.hboxBar.addWidget(self.slider)
        self.hboxBar.addWidget(self.totalLable)

    def setVideo(self, video):
        self.video = video
        self.player.setVideo(video)
        self.player.play()

    def startValueChanged(self, number):
        self.player.position(number)

    def onClickPlay(self):
        if self.player.playing:
            self.player.stop()
        else:
            self.player.play()

    def releaseSlider(self):
        if self.slder_video_pressed:
            self.player.play()

        self.slder_video_pressed = False

    def pressSlider(self):
        if self.player.playing:
            self.slder_video_pressed = True
        self.player.stop()
        self.player.position(self.slider.value())

    def moveSlider(self, position):
        self.player.position(position)

    def playerProgressChanged(self, progress):
        self.currentLabel.setText(self.player.format_time(progress))
        self.slider.setValue(progress)

    def playerStateChanged(self, state):
        if state == Success:
            print("加载视频成功")
            total_second = self.player.total_second
            self.totalLable.setText(self.player.format_time(total_second))
            self.slider.setMaximum(total_second)

        elif state == Failure:
            print("加载视频失败")
        elif state == Play:
            self.playButton.setText("暂停")
        elif state == Stop:
            self.playButton.setText("播放")
        elif state == Pause:
            self.playButton.setText("播放")
        elif state == Start:
            self.playButton.setText("暂停")
